#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: robot_demo.py 
@version:
@time: 2022/01/10
"""
import requests
import json
import pprint
from TapClientCore.path_conf import PathConf


class CodingBugReport:
    # Daas
    Daas = {'Id': 342870, 'Name': 'tapdata', 'TeamId': 155077, 'Type': 2}
    DFS = {'Id': 8438504, 'Name': 'dfs', 'TeamId': 155077, 'Type': 2}
    URL = 'https://e.coding.net'
    defaultId = 8136627
    THIS_PATH = f'{PathConf.PROJECT_PATH}/TapClientCore/report_bug'
    DEFECT_TYPE_ID = f'{THIS_PATH}/DaasDefectTypeIdList.json'
    DFS_DEFECT_TYPE_ID = f'{THIS_PATH}/DFSDefectTypeIdList.json'
    DefectTypeId = None
    PROJECT_MODULE_ID = f'{THIS_PATH}/DaasProjectModuleId.json'
    DFS_PROJECT_MODULE_ID = f'{THIS_PATH}/DFSProjectModuleId.json'
    ProjectModuleId = None
    ASSIGNEE_ID = f'{THIS_PATH}/AssigneeId.json'
    AssigneeId = None
    ITERATION_CODE = f'{THIS_PATH}/DaasIterationCode.json'
    DFS_ITERATION_CODE = f'{THIS_PATH}/DFSIterationCode.json'
    IterationCode = None

    def __init__(self, token='91f9dd530feedfea219b8c67a165e8387a8af72b', production='daas'):
        self.headers = {
            "Authorization": "token " + token,
        }
        self.pro = production
        self.read_config_info(production)

    @classmethod
    def _read(cls, path):
        with open(path, 'r', encoding='utf-8') as f:
            return json.loads(f.read(), encoding='utf-8')

    def read_config_info(self, production):
        self.AssigneeId = self._read(self.ASSIGNEE_ID)
        if production == 'daas':
            # daas
            self.DefectTypeId = self._read(self.DEFECT_TYPE_ID)
            self.ProjectModuleId = self._read(self.PROJECT_MODULE_ID)
            self.IterationCode = self._read(self.ITERATION_CODE)
        if production == 'dfs':
            # dfs
            self.DefectTypeId = self._read(self.DFS_DEFECT_TYPE_ID)
            self.ProjectModuleId = self._read(self.DFS_PROJECT_MODULE_ID)
            self.IterationCode = self._read(self.DFS_ITERATION_CODE)

    def get_defect_type_id_by_name(self, name):
        for one in self.DefectTypeId:
            if one['name'] == name:
                return one['id']
        raise Exception

    def get_project_module_id_by_name(self, name):
        for one in self.ProjectModuleId:
            if one['name'] == name:
                return one['id']
        raise Exception

    def get_assignee_id_by_name(self, name):
        for one in self.AssigneeId:
            if one['name'] == name:
                return one['user_id']

    def get_iteration_code_by_name(self, name):
        for one in self.IterationCode:
            if one['name'] == name:
                return one['code']
        raise Exception

    def get_user_info(self):
        payload = {
            "Action": "DescribeCodingCurrentUser"
        }
        return requests.post(f'{self.URL}/open-api?Action=DescribeCodingCurrentUser',
                             headers=self.headers, json=payload).json()

    def report_bug(self, **kwargs):
        """
        open url: "https://e.coding.net/open-api"
        ProjectName: {"tapdata": {"iteration": "18869","human": "Sprint #46",}}
        bug_title: ''
        priority: "0":低， "1"：中 "2"：高 "3"：紧急
        DefectTypeId:
        ProjectModuleId:
        AssigneeId:
        IterationCode:
        CustomFieldValues:
        :param kwargs:
        :return:
        """
        payload = None
        if self.pro == 'daas':
            ProjectName = kwargs.get('ProjectName')
            bug_title = kwargs.get('bug_title')
            Priority = kwargs.get('Priority')
            DefectTypeId = self.get_defect_type_id_by_name(kwargs.get('DefectTypeId'))
            ProjectModuleId = self.get_project_module_id_by_name(kwargs.get('ProjectModuleId'))
            AssigneeId = self.get_assignee_id_by_name(kwargs.get('AssigneeId', self.defaultId))
            IterationCode = self.get_iteration_code_by_name(kwargs.get('IterationCode'))
            CustomFieldValues = kwargs.get('CustomFieldValues')
            Description = kwargs.get('Description')
            payload = {
                'Action': 'CreateIssue',
                'ProjectName': ProjectName,  # 缺陷名字
                "Type": "DEFECT",  # 表单类型
                "Name": bug_title,  # 标题
                "Priority": Priority,  # 优先级
                "DefectTypeId": DefectTypeId,  # 缺陷类型
                "ProjectModuleId": ProjectModuleId,  # 项目模块
                "AssigneeId": AssigneeId,  # 处理人
                "IterationCode": IterationCode,  # 迭代
                "CustomFieldValues": CustomFieldValues,
                "Description": Description
            }
        if self.pro == 'dfs':
            ProjectName = kwargs.get('ProjectName')
            bug_title = kwargs.get('bug_title')
            Priority = kwargs.get('Priority')
            DefectTypeId = self.get_defect_type_id_by_name(kwargs.get('DefectTypeId'))
            ProjectModuleId = self.get_project_module_id_by_name(kwargs.get('ProjectModuleId'))
            AssigneeId = self.get_assignee_id_by_name(kwargs.get('AssigneeId', self.defaultId))
            IterationCode = self.get_iteration_code_by_name(kwargs.get('IterationCode'))
            CustomFieldValues = kwargs.get('CustomFieldValues')
            Description = kwargs.get('Description')
            payload = {
                'Action': 'CreateIssue',
                'ProjectName': ProjectName,  # 缺陷名字
                "Type": "DEFECT",  # 表单类型
                "Name": bug_title,  # 标题
                "Priority": Priority,  # 优先级
                "DefectTypeId": DefectTypeId,  # 缺陷类型
                "ProjectModuleId": ProjectModuleId,  # 项目模块
                "AssigneeId": AssigneeId,  # 处理人
                "IterationCode": IterationCode,  # 迭代
                "CustomFieldValues": CustomFieldValues,
                "Description": Description
            }
        response = requests.post(url=f"{self.URL}/open-api?Action=CreateIssue",
                                 headers=self.headers,
                                 json=payload).json()
        return response

    def report_bug_for_auto_test(self, **kwargs):
        """
        production:
        bug_title:
        des:
        bug_level:
        bug_type:
        bug_man:
        bug_iteration:
        version:

        :param kwargs:
        :return:
        """
        production = kwargs.get('production', 'tapdata')
        bug_title = kwargs.get('bug_title', '')
        bug_level = kwargs.get('bug_level', '0')
        bug_type = kwargs.get('bug_type', '功能缺陷')
        bug_module = kwargs.get('bug_module', '数据迁移')
        bug_man = kwargs.get('bug_man', 'Jackin黄佳钦')
        bug_iteration = kwargs.get('bug_iteration', 'Q 101')
        version = kwargs.get('version', 'v1.30')
        des = kwargs.get('des', '自动化案例执行失败')
        FORMAT = None
        if self.pro == 'daas':
            FORMAT = {
                'ProjectName': production,
                'bug_title': f'【自动化案例】{bug_title}',
                "Priority": bug_level,
                "DefectTypeId": bug_type,  # 缺陷类型
                "ProjectModuleId": bug_module,  # 项目模块
                "AssigneeId": bug_man,  # 处理人
                "IterationCode": bug_iteration,  # 迭代
                "CustomFieldValues": [
                    {
                        "id": 35563185,
                        "content": "15201"
                    },

                    {
                        "id": 35563186,
                        "content": version, },
                    {
                        'id': 36119765,
                        'content': '120949'
                    }],
                "Description": des
            }
            if self.pro == 'dfs':
                FORMAT = {
                    'ProjectName': production,
                    'bug_title': f'【自动化案例】{bug_title}',
                    "Priority": bug_level,
                    "DefectTypeId": bug_type,  # 缺陷类型
                    "ProjectModuleId": bug_module,  # 项目模块
                    "AssigneeId": bug_man,  # 处理人
                    "IterationCode": bug_iteration,  # 迭代
                    "CustomFieldValues": [
                        {
                            "id": 35911512,
                            "content": version, }],
                    "Description": des
                }
            print(FORMAT)
            return self.report_bug(**FORMAT)
